package com.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server1 {
    public static void main(String[] args) {
        final int PORT = 8888;

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务端已启动，等待客户端连接...");

            while (true) {
                // 接受客户端连接
                try (Socket clientSocket = serverSocket.accept();
                     // 获取输入输出流
                     BufferedReader in = new BufferedReader(
                             new InputStreamReader(clientSocket.getInputStream()));
                     PrintWriter out = new PrintWriter(
                             clientSocket.getOutputStream(), true)) {  // true 开启自动刷新

                    System.out.println("客户端已连接: " + clientSocket.getInetAddress());

                    // 读取客户端消息
                    String clientMessage;
                    while ((clientMessage = in.readLine()) != null) {
                        System.out.println("收到客户端消息: " + clientMessage);

                        // 处理消息：转大写并返回
                        String response = clientMessage.toUpperCase();
                        out.println(response);  // 使用 PrintWriter 发送响应
                        System.out.println("已返回响应: " + response);
                    }
                } catch (IOException e) {
                    System.err.println("客户端连接异常: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("服务端启动失败: " + e.getMessage());
        }
    }
}
